package com.leetcodehot.problems;

import java.util.*;

public class problems103 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.addFirst(root);
        boolean flag = true;
        while (!deque.isEmpty()) {
            int count = deque.size();
            List<Integer> list = new ArrayList<>();
            while (count-- > 0) {
                TreeNode first = deque.pollFirst();
                list.add(first.val);
                if (first.left != null) deque.addLast(first.left);
                if (first.right != null) deque.addLast(first.right);
            }
            if (!flag) {
                Collections.reverse(list);
            }
            res.add(list);
            flag = !flag;
        }
        return res;
    }
}
